package com.ltu.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FileUtil {
	public static long getFileSize(String path) { 
		  FileChannel fc= null; 
		  long  fileSize=0;
		  try { 
		    File f= new File(path); 
		    if (f.exists() && f.isFile()){ 
		      FileInputStream fis= new FileInputStream(f); 
		      fc= fis.getChannel(); 
		        fileSize=fc.size()/1024;
		    }else{ 
		    	log.info("file doesn't exist or is not a file"); 
		    } 
		  } catch (FileNotFoundException e) { 
			  e.printStackTrace();
		  } catch (IOException e) { 
			  e.printStackTrace();
		  } finally { 
		    if (null!=fc){ 
		      try{ 
		        fc.close(); 
		        
		      }catch(IOException e){ 
		    	  e.printStackTrace();
		      } 
		    }  
		    return fileSize; 
		  }
	} 
	
	/**
	 * pdf生成水印
	 * @param srcPdfPath       插入前的文件路径
	 * @param tarPdfPath       插入后的文件路径
	 * @param WaterMarkContent 水印文案
	 * @param numberOfPage     每页需要插入的条数
	 * @throws Exception
	 */
	public static void addWaterMark(String srcPdfPath, String tarPdfPath, String WaterMarkContent, int numberOfPage)
			throws Exception {
		PdfReader reader = new PdfReader(srcPdfPath);
		PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(tarPdfPath));
		PdfGState gs = new PdfGState();

		try {
			// 设置字体
			BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			// 设置透明度
			gs.setFillOpacity(0.7f);
			int total = reader.getNumberOfPages() + 1;
			PdfContentByte content;
			for (int i = 1; i < total; i++) {
				content = stamper.getOverContent(i);
				content.beginText();
				content.setGState(gs);
				// 水印颜色
				content.setColorFill(BaseColor.DARK_GRAY);
				// 水印字体样式和大小
				content.setFontAndSize(font, 24);
				// 插入水印 循环每页插入的条数
				for (int j = 0; j < numberOfPage; j++) {
					content.showTextAligned(Element.ALIGN_CENTER, WaterMarkContent, 150, 200 * (j + 1), 45);
				}
				for (int j = 0; j < numberOfPage; j++) {
					content.showTextAligned(Element.ALIGN_CENTER, WaterMarkContent, 500, 200 * (j + 1), 45);
				}
				for (int j = 0; j < numberOfPage; j++) {
					content.showTextAligned(Element.ALIGN_CENTER, WaterMarkContent, 850, 200 * (j + 1), 45);
				}

				content.endText();
			} 
		} finally {
			stamper.close();
		}
		
		System.out.println("PDF水印添加完成！");
	}

	
}
